//
//  107. 二叉树的层序遍历II.swift
//  LeetCodeTrain
//
//  Created by rjb on 2021/8/18.
//  Copyright © 2021 rjb. All rights reserved.
//

import Foundation
class Solution107 {
    // 二叉树的层序遍历
    func levelOrderBottom(_ root: TreeNode?) -> [[Int]] {
        var result:[[Int]] = []
        guard let root = root else {
            return result
        }
        var queue: [TreeNode] = [root]
        while !queue.isEmpty {
            var size = queue.count
            var layerArray:[Int] = []
            while size > 0 {
                let first = queue.removeFirst()
                layerArray.append(first.val)
                if let left = first.left {
                    queue.append(left)
                }
                if let right = first.right {
                    queue.append(right)
                }
                size -= 1
            }
            result.insert(layerArray, at: 0)
        }
        return result
    }
    static func test() {
        
    }
}
